<?php

function dbOpenConnection()
{
  require("defs.inc.php");
   $DB_CONNECTION = mysql_connect($DB_HOST, $DB_USERNAME, $DB_PASSWORD) or die('Connessione fallita' . mysql_error());
   mysql_select_db('bazar') or die('Selezione Database' . mysql_error());

}

function dbCloseConnection()
{
  global $DB_CONNECTION;
  mysql_close($DB_CONNECTION);
}

function dbSendQuery($query)
{
  dbOpenConnection();
  $result=mysql_query($query) or die('Query' . mysql_error());
  return $result;
}

function dbisValid($user,$pass)
{
  if($user =="" || $pass == "")
    return NULL;

  $query="SELECT id FROM utente WHERE username = '$user' AND password = password('$pass')";

  $result=dbSendQuery($query);

  if(mysql_num_rows($result) != 0)
  {
    $id=mysql_fetch_array($result);
    $id=$id['id'];
  }
  else
  {
    $id=NULL;
  }

  return $id;
}

function dbaddUser($user,$pass,$nome,$cognome,$indirizzo)
{
  //Verifica che l'utente non esista già
  $QUERY="SELECT * FROM utente WHERE username='$user'";

  $result=dbSendQuery($QUERY);

  if(mysql_num_rows($result)!=0)
  {
   return NULL;
  }

  //Inserimento nuovo utente
  $QUERY="INSERT INTO utente (nome,cognome,indirizzo,username,password)
          VALUES ('$nome','$cognome','$indirizzo','$user',password('$pass'))";

  dbSendQuery($QUERY);

  //Ricezione id nuovo utente
  $QUERY="select id from utente where username='$user'";
  return dbSendQuery($QUERY);
}


function dbSearchContentString($searchString)
{
  $tokens = explode(" ", $searchString);

  $QUERY = "
  SELECT oggetto.id,
         oggetto.nome,
         oggetto.descrizione,
         oggetto.id_utente,
         oggetto.categoria,
         asta.id AS id_asta

  FROM oggetto, asta WHERE UNIX_TIMESTAMP(end_ts) > UNIX_TIMESTAMP(NOW()) AND asta.id_oggetto = oggetto.id AND (oggetto.nome LIKE '%$tokens[0]%'";

  for($i=1;$i<count($tokens);$i++)
  {
    $QUERY .=" OR oggetto.nome LIKE '%".$tokens[$i]."%'";
  }

  for($i=0;$i<count($tokens);$i++)
  {
    $QUERY .=" OR oggetto.descrizione LIKE '%".$tokens[$i]."%'";
  }

  $QUERY.= "  )ORDER BY asta.start_ts DESC";
  return dbSendQuery($QUERY);
}


function dbGetLastCategoryItems($id_padre)
{
  if($id_padre == NULL)
  {
     $QUERY = "
     SELECT oggetto.id AS id_oggetto,
            oggetto.nome AS nome_oggetto,
            asta.id AS id_asta
     FROM oggetto, asta
     WHERE oggetto.id = asta.id_oggetto AND
           UNIX_TIMESTAMP(asta.end_ts) > UNIX_TIMESTAMP(NOW())";
  }
  else
  {
    $QUERY = "
    SELECT oggetto.id AS id_oggetto,
            oggetto.nome AS nome_oggetto,
            asta.id AS id_asta
     FROM oggetto, asta
     WHERE oggetto.id = asta.id_oggetto AND
           UNIX_TIMESTAMP(asta.end_ts) > UNIX_TIMESTAMP(NOW()) AND
           oggetto.categoria = $id_padre";
  }

  $QUERY.=" LIMIT 6";

  return dbSendQuery($QUERY);
}

function dbGetSubCategories($id_padre)
{
  if ($id_padre == NULL)
    $QUERY = "SELECT id,nome FROM categoria WHERE padre IS NULL";
  else
    $QUERY = "SELECT id,nome FROM categoria WHERE padre = $id_padre";

  return dbSendQuery($QUERY);
}

function dbGetRootCategories()
{
  return dbGetSubCategories(NULL);
}

function dbCountSubCategories($id_padre)
{
  if ($id_padre == NULL)
    $QUERY = "SELECT COUNT(*) AS numero FROM categoria WHERE padre IS NULL";
  else
    $QUERY = "SELECT COUNT(*) AS numero FROM categoria WHERE padre = $id_padre";

  $res = mysql_fetch_array(dbSendQuery($QUERY));

  return $res["numero"];
}

function dbCountCategoryObjects($id_padre)
{
  if ($id_padre == NULL)
  {
    $QUERY = "SELECT COUNT(*) AS numero FROM oggetto WHERE id IN
              (SELECT id_oggetto FROM asta
               WHERE UNIX_TIMESTAMP(end_ts) > UNIX_TIMESTAMP(NOW()))";

    $res = mysql_fetch_array(dbSendQuery($QUERY));
    return $res["numero"];
  }
  else
  {
    $QUERY = "SELECT COUNT(*) AS numero FROM oggetto
              WHERE categoria = $id_padre
              AND id IN
              (SELECT id_oggetto FROM asta
               WHERE UNIX_TIMESTAMP(end_ts) > UNIX_TIMESTAMP(NOW()))";

    $res = mysql_fetch_array(dbSendQuery($QUERY));
    $count = $res["numero"];

    $figli = dbSendQuery("SELECT id FROM categoria WHERE padre = $id_padre");

    while($riga = mysql_fetch_array($figli))
    {
      $figlio = $riga["id"];
      $count += dbCountCategoryObjects($figlio);
    }

    return $count;
  }
}

function dbCountAllCategoryObjects($id_padre)
{
  if ($id_padre == NULL)
  {
    $QUERY = "SELECT COUNT(*) AS numero FROM oggetto";

    $res = mysql_fetch_array(dbSendQuery($QUERY));
    return $res["numero"];
  }
  else
  {
    $QUERY = "SELECT COUNT(*) AS numero FROM oggetto
              WHERE categoria = $id_padre";

    $res = mysql_fetch_array(dbSendQuery($QUERY));
    $count = $res["numero"];

    $figli = dbSendQuery("SELECT id FROM categoria WHERE padre = $id_padre");

    while($riga = mysql_fetch_array($figli))
    {
      $figlio = $riga["id"];
      $count += dbCountAllCategoryObjects($figlio);
    }

    return $count;
  }
}

function dbGetCategoryName($id_cat)
{
  $QUERY = "SELECT nome FROM categoria WHERE id = $id_cat";
  $res = dbSendQuery($QUERY);
  $num = mysql_num_rows($res);

  if($num < 1) return NULL;
  else
  {
    $riga = mysql_fetch_array($res);
    return $riga["nome"];
  }
}

function dbGetItem($id)
{
  $QUERY="SELECT oggetto.id as idO,
  oggetto.nome as nomeO,
  oggetto.descrizione as descrizioneO,
  oggetto.categoria as categoriaO,
  utente.username as usernameU,
  utente.id as idU,
  utente.reputazione as reputazioneU

      FROM oggetto,utente WHERE oggetto.id=$id AND id_utente=utente.id";

  return dbSendQuery($QUERY);
}



function dbGetLastItems($sort,$startItem,$num)
{
  $QUERY="SELECT
      asta.id as idA,
      asta.start_ts as start_tsA,
      asta.end_ts as end_tsA,
      asta.base as baseA,
      oggetto.id as idO,
      oggetto.nome as nomeO,
      oggetto.categoria as categoriaO,
      utente.username as usernameU,
      utente.id as idU,
      utente.reputazione as reputazioneU,
      categoria.id as idC,
      categoria.nome as nomeC
      FROM oggetto,asta,utente,categoria
      WHERE
      oggetto.id = id_oggetto AND
      oggetto.id_utente = utente.id AND

      oggetto.categoria = categoria.id AND
      UNIX_TIMESTAMP(asta.end_ts) > UNIX_TIMESTAMP(NOW())
      ORDER BY ";

  switch($sort)
  {
    default:
      case "end_ts":$QUERY .="asta.end_ts ";
      break;
      case "seller":$QUERY .="utente.username ";
      break;
      case "item": $QUERY .="oggetto.nome ";
      break;
      case "base": $QUERY .="asta.base ";
      break;
      case "start_ts": $QUERY .="asta.start_ts DESC ";
      break;
  }
  $QUERY.="LIMIT $startItem,$num";
  return dbSendQuery($QUERY);
}


function dbGetUserFromId($id)
{
  $QUERY = "SELECT * FROM utente WHERE id=$id";

  $result=dbSendQuery($QUERY);
  if(mysql_num_rows($result)!=1)
  {
    header("Location: http://".$_SERVER['HTTP_HOST']
        .dirname($_SERVER['PHP_SELF'])."/error.php?errid=14");

  }
  return mysql_fetch_array($result);
}


function dbGetRecentAuctionsIds()
{
  $QUERY = "SELECT id FROM asta WHERE UNIX_TIMESTAMP(end_ts) > UNIX_TIMESTAMP(NOW()) ORDER BY end_ts";

  return dbSendQuery($QUERY);
}


function dbGetOffersPerAuction($id_asta)
{
  $res = dbSendQuery("SELECT COUNT(*) AS conteggio FROM offerta WHERE offerta.id_asta = $id_asta");

  $riga = mysql_fetch_array($res);
  return $riga["conteggio"];
}


function dbGetOffers($id_asta)
{
  $QUERY="
  SELECT offerta.id AS id_offerta,
         importo,
         timestamp,
         id_utente AS id_offerente,
         username AS username_offerente,
         reputazione AS rept_offerente
  FROM offerta, utente
  WHERE id_utente = utente.id AND
        id_asta = $id_asta
  ORDER BY importo DESC";

  return dbSendQuery($QUERY);
}


function dbGetAuctionData($id_asta)
{
  $QUERY = "
  SELECT oggetto.id         AS id_oggetto,
         oggetto.nome       AS nome_oggetto,
         oggetto.descrizione AS descrizione_oggetto,
         categoria.id       AS id_categoria,
         categoria.nome     AS nome_categoria,
         CONCAT(
                TIMEDIFF(asta.end_ts, NOW()) DIV 24, ' gg ',
                MOD(TIME_FORMAT(TIMEDIFF(asta.end_ts, NOW()), '%H'), 24), ' h ',
                TIME_FORMAT(TIMEDIFF(asta.end_ts, NOW()), '%i'), ' m')
                AS tempo_rimanente,
         utente.id          AS id_utente,
         utente.username    AS username,
         utente.reputazione AS reputazione,
         asta.base          AS base,
         asta.riserva       AS riserva,
         asta.start_ts      AS start_ts,
         asta.end_ts        AS end_ts,
         numero_offerte.n   AS conteggio
  FROM   asta, oggetto, utente, categoria,
         (
           SELECT COUNT(*) AS n FROM offerta WHERE offerta.id_asta = $id_asta
         ) AS numero_offerte
  WHERE  asta.id_oggetto = oggetto.id AND
         oggetto.id_utente = utente.id AND
         oggetto.categoria = categoria.id AND
         asta.id = $id_asta
  ";

  return dbSendQuery($QUERY);
}


function dbGetBestOfferData($id_asta)
{
  //riga rimossa:
  // UNIX_TIMESTAMP(asta.end_ts) > UNIX_TIMESTAMP(NOW()) AND

  $QUERY = "
  SELECT * FROM
  (
  SELECT offerta.id_asta    AS id_asta,
         offerta.id         AS id_offerta,
         offerta.id_utente  AS id_offerente,
         utente.username    AS username_offerente,
         utente.reputazione AS rept_offerente,
         migliori.importo   AS importo
  FROM offerta, asta, utente,
  (
    SELECT id_asta, MAX(importo) AS importo
    FROM offerta
    GROUP BY id_asta
  ) AS migliori
  WHERE migliori.id_asta = offerta.id_asta = asta.id   AND
        offerta.importo = migliori.importo AND
        offerta.id_utente = utente.id
  ) AS info_offerta
  WHERE info_offerta.id_asta = $id_asta
  ";

  return dbSendQuery($QUERY);
}


function dbCreateObject($nome, $descrizione, $id_utente, $id_categoria)
{
  $nome = addslashes($nome);
  $descrizione = addslashes($descrizione);
  $QUERY = "INSERT INTO oggetto VALUES(NULL, '{$nome}', '{$descrizione}', NULL, $id_utente, $id_categoria)";
  dbSendQuery($QUERY);
  return mysql_insert_id();
}


function dbCreateAuction($giorni, $base, $riserva, $id_oggetto)
{
  $QUERY = "INSERT INTO asta VALUES(NULL, NOW(), ADDDATE(NOW(), $giorni), $base, $riserva, NULL, NULL, $id_oggetto)";
  dbSendQuery($QUERY);
  return mysql_insert_id();
}


function dbStoreImage($post_file_tmp, $id_oggetto)
{
  $dati = addslashes(file_get_contents($post_file_tmp));
  $dimensioni = getimagesize($post_file_tmp);

  $QUERY = "INSERT INTO immagine VALUES(NULL, '{$dimensioni['mime']}', '{$dati}', '{$dimensioni[3]}', '{$dimensioni[0]}', '{$dimensioni[1]}')";
  dbSendQuery($QUERY);
  $id_img = mysql_insert_id();

  $QUERY = "UPDATE oggetto SET id_immagine = $id_img WHERE id = $id_oggetto";
  dbSendQuery($QUERY);

  return $id_img;
}


function dbGetImageDataFromObject($id_oggetto)
{
  $QUERY = "
  SELECT immagine.id AS id,
         immagine.tipo AS tipo,
         immagine.dati AS dati,
         immagine.dimensioni AS dimensioni
  FROM oggetto, immagine
  WHERE oggetto.id = $id_oggetto AND
        oggetto.id_immagine = immagine.id
  ";
  return dbSendQuery($QUERY);
}


function dbGetImageDimensionStringFromObject($id_oggetto)
{
  $QUERY = "
  SELECT immagine.dimensioni, immagine.width, immagine.height
  FROM oggetto, immagine
  WHERE oggetto.id = $id_oggetto AND
        oggetto.id_immagine = immagine.id
  ";

  $res = dbSendQuery($QUERY);

  if(mysql_num_rows($res) > 0)
  {
    $riga = mysql_fetch_array($res);
    
    if ($riga['width']>500)
    {
      return "width=\"500px\"";
    }
    if ($riga['height']>400)
    {
      return "height=\"400px\"";
    }
    else
    {
      return $riga['dimensioni'];
    }
  }
  else return "";
}


function dbGetImageDimensionsFromObject($id_oggetto)
{
  $QUERY = "
  SELECT immagine.width AS width,
         immagine.height AS height
  FROM oggetto, immagine
  WHERE oggetto.id = $id_oggetto AND
        oggetto.id_immagine = immagine.id
  ";

  $res = dbSendQuery($QUERY);

  if(mysql_num_rows($res) > 0)
  {
    $riga = mysql_fetch_array($res);
    $dims[] = $riga['width'];
    $dims[] = $riga['height'];
    return $dims;
  }
  else return NULL;
}


function dbGetImageData($id_img)
{
  $QUERY = "SELECT * FROM immagine WHERE id = $id_img";
  return dbSendQuery($QUERY);
}


function dbGetImageDimensionString($id_img)
{
  $QUERY = "SELECT dimensioni FROM immagine WHERE id = $id_img";

  $res = dbSendQuery($QUERY);

  if(mysql_num_rows($res) > 0)
  {
    $riga = mysql_fetch_array($res);
    return $riga['dimensioni'];
  }
  else return "";
}


function dbGetImageDimensions($id_img)
{
  $QUERY = "SELECT width, height FROM immagine WHERE id = $id_img";

  $res = dbSendQuery($QUERY);

  if(mysql_num_rows($res) > 0)
  {
    $riga = mysql_fetch_array($res);
    $dims[] = $riga['width'];
    $dims[] = $riga['height'];
    return $dims;
  }
  else return NULL;
}


function dbObjectHasImage($id_oggetto)
{
  $QUERY = "SELECT id_immagine FROM oggetto WHERE id = $id_oggetto AND id_immagine IS NOT NULL";
  $res = dbSendQuery($QUERY);

  return mysql_num_rows($res) > 0;
}

function dbGetUserItems($userid)
{
  $QUERY = "SELECT * FROM oggetto WHERE id_utente = $userid";

  return dbSendQuery($QUERY);
}

function dbUserType($userid)
{
  $QUERY = "SELECT tipo FROM utente WHERE id = $userid";

  $result = dbSendQuery($QUERY);
  $type = mysql_fetch_array($result);
  return $type['tipo'];
}

function dbDoOffer($importo, $id_asta, $id_utente)
{
  $QUERY="INSERT INTO offerta VALUES(NULL, $importo, NOW(), $id_asta, $id_utente)";
  dbSendQuery($QUERY);

  return mysql_insert_id();
}

function dbSetInterest($id_utente, $id_categoria)
{
  $QUERY = "
  INSERT INTO interesse VALUES($id_utente, $id_categoria)
  ";
  dbSendQuery($QUERY);
}

function dbUnsetInterest($id_utente, $id_categoria)
{
  $QUERY = "
  DELETE FROM interesse WHERE id_utente = $id_utente AND categoria = $id_categoria
  ";
  dbSendQuery($QUERY);
}

function dbGetUserInterests($id_utente)
{
  $QUERY = "
  SELECT categoria.id AS id_categoria,
         categoria.nome AS nome_categoria
  FROM interesse, categoria
  WHERE interesse.categoria = categoria.id AND
        id_utente = $id_utente
  ";
  return dbSendQuery($QUERY);
}

function dbIsUserInterested($id_utente, $id_categoria)
{
  $QUERY = "
  SELECT * FROM interesse WHERE id_utente = $id_utente AND categoria = $id_categoria
  ";
  $res = dbSendQuery($QUERY);

  return mysql_num_rows($res) > 0;
}


function dbSetWatchAuction($id_utente, $id_asta)
{
  $QUERY = "
  INSERT INTO osservazione VALUES($id_utente, $id_asta)
  ";
  dbSendQuery($QUERY);
}

function dbUnWatchAuction($id_utente, $id_asta)
{
  $QUERY = "
  DELETE FROM osservazione WHERE id_utente = $id_utente AND id_asta = $id_asta
  ";
  dbSendQuery($QUERY);
}

function dbGetUserWatchedAuctions($id_utente)
{
  $QUERY = "
  SELECT id_asta,
         CONCAT(
                TIMEDIFF(asta.end_ts, NOW()) DIV 24, ' gg ',
                MOD(TIME_FORMAT(TIMEDIFF(asta.end_ts, NOW()), '%H'), 24), ' h ',
                TIME_FORMAT(TIMEDIFF(asta.end_ts, NOW()), '%i'), ' m')
                AS tempo_rimanente,
         oggetto.nome AS nome_oggetto
  FROM osservazione, asta, oggetto
  WHERE osservazione.id_asta = asta.id AND
        asta.id_oggetto = oggetto.id AND
        osservazione.id_utente = $id_utente
  ORDER BY asta.end_ts DESC
  ";
  return dbSendQuery($QUERY);
}

function dbIsUserWatchingAuction($id_utente, $id_asta)
{
  $QUERY = "
  SELECT * FROM osservazione WHERE id_utente = $id_utente AND id_asta = $id_asta
  ";
  $res = dbSendQuery($QUERY);

  return mysql_num_rows($res) > 0;
}

function dbActiveAuction($id_asta)
{
  $QUERY = "
  SELECT *
  FROM asta
  WHERE id = $id_asta AND
        UNIX_TIMESTAMP(end_ts) > UNIX_TIMESTAMP(NOW())";

  $res = dbSendQuery($QUERY);
  return mysql_num_rows($res) > 0;
}

function dbIsObjectCurrentlyOnSale($id_oggetto)
{
  $QUERY = "
  SELECT * FROM asta
  WHERE id_oggetto = $id_oggetto AND
        UNIX_TIMESTAMP(end_ts) > UNIX_TIMESTAMP(NOW())
  ";
  $res = dbSendQuery($QUERY);

  return mysql_num_rows($res) > 0;
}

function dbIsUserObjectOwner($id_utente, $id_oggetto)
{
  $QUERY = "
  SELECT * FROM oggetto
  WHERE id = $id_oggetto AND
        id_utente =  $id_utente
  ";
  $res = dbSendQuery($QUERY);

  return mysql_num_rows($res) > 0;
}

function dbGetWorstUser($minReputation)
{
  $QUERY = "SELECT *
            FROM
            (
              SELECT DISTINCT utente.id AS idU,
                              utente.nome AS nomeU,
                              utente.cognome AS cognomeU,
                              utente.indirizzo AS indirizzoU,
                              utente.username AS usernameU,
                              utente.diffida_ts AS diffida_tsU,
                              utente.reputazione AS reputazioneU,
                              utente.tipo AS tipoU,
                              CONCAT(TIMEDIFF(diffida_ts, NOW()) DIV 24, ' gg ')
                              AS tempo_rimanente
              FROM utente,asta,oggetto
              WHERE utente.id = oggetto.id_utente AND
                    asta.id_oggetto = oggetto.id
            ) AS venditori
            WHERE reputazioneU < $minReputation ORDER BY reputazioneU,nomeU";

  return dbSendQuery($QUERY);
}

function dbDiffUser($id,$days)
{
  $QUERY="UPDATE utente SET diffida_ts=ADDDATE(NOW(),$days) WHERE id=$id AND diffida_ts IS NULL";
  dbSendQuery($QUERY);
}

function dbRevokeDiffUser($id)
{
  $QUERY="UPDATE utente SET diffida_ts=NULL WHERE id=$id";
  dbSendQuery($QUERY);
}

function dbUpdateRep($id,$factor)
{
  $QUERY="UPDATE utente SET reputazione=reputazione+$factor WHERE id=$id";

  dbSendQuery($QUERY);
}

function dbIdisDiff($id)
{
  $QUERY="SELECT CONCAT(TIMEDIFF(diffida_ts, NOW()) DIV 24, ' giorni ')
                 AS tempo_rimanente
          FROM utente WHERE id=$id AND diffida_ts>NOW()";
  return dbSendQuery($QUERY);
}

function dbGetDiffUser()
{
  $QUERY="SELECT *
          FROM utente WHERE diffida_ts IS NOT NULL";
  return dbSendQuery($QUERY);
}

function dbGetUser($sort,$start,$num)
{


  $QUERY="SELECT *,
          CONCAT(TIMEDIFF(diffida_ts, NOW()) DIV 24, ' giorni ') AS tempo_rimanente
          FROM utente,(SELECT COUNT(*) AS numTot  FROM utente) AS count ";

  switch($sort)
  {
    default:$QUERY.="";
  }

  $QUERY.="ORDER BY username ";

  if($start!=null && $num!=null)
  {
    $QUERY.="LIMIT $start,$num ";
  }

  return dbSendQuery($QUERY);
}


function dbIsUserWinner($id_utente, $id_asta)
{
  $res = dbGetBestOfferData($id_asta);

  if(mysql_num_rows($res) < 1) return false;

  $riga = mysql_fetch_array($res);
  return $id_utente == $riga['id_offerente'];
}


function dbUpdateUserProfile($id,$nome,$cognome,$indirizzo)
{
  $QUERY="UPDATE utente SET nome='$nome',cognome='$cognome',indirizzo='$indirizzo' WHERE id=$id";
  dbSendQuery($QUERY);
}

function dbUpdateUserPass($id,$pass)
{
  $QUERY="UPDATE utente SET password=password('$pass') WHERE id=$id";
  dbSendQuery($QUERY);
}

function dbGetAuctionRating($id_asta)
{
  $QUERY="SELECT giudizio, commento
          FROM asta
          WHERE id = $id_asta AND giudizio IS NOT NULL AND commento IS NOT NULL";
  return dbSendQuery($QUERY);
}

function dbSetAuctionRating($id_asta, $giudizio, $commento)
{
  $commento = addslashes($commento);

  $QUERY = "
  UPDATE asta SET giudizio = $giudizio, commento = '{$commento}' WHERE id = $id_asta
  ";

  dbSendQuery($QUERY);
}

function dbGetAllAuctionsPerItem($id_oggetto)
{
  $QUERY = "
  SELECT id AS id_asta,
         UNIX_TIMESTAMP(end_ts) > UNIX_TIMESTAMP(NOW()) AS attiva,
         end_ts
  FROM asta WHERE id_oggetto = $id_oggetto
  ORDER BY end_ts DESC
  ";

  return dbSendQuery($QUERY);
}

function dbInsertCat($father,$name)
{
  $QUERY="SELECT * FROM categoria WHERE nome=\"$name\"";
  $result=dbSendQuery($QUERY);
  
  if(mysql_num_rows($result)==0)
  {
    $QUERY="INSERT INTO categoria(nome,padre) VALUES ('$name',$father)";
    dbSendQuery($QUERY);
    return TRUE;
  }
  else
  {
    return FALSE;
  }
}

function dbRemCat($id)
{
  $QUERY="DELETE FROM categoria WHERE id=$id";;
  dbSendQuery($QUERY);
}

function dbUpdateCat($id,$newname)
{
  $QUERY="UPDATE categoria SET nome='$newname' WHERE id=$id";
  dbSendQuery($QUERY);
}

function dbGetFatherCat($id)
{
  $QUERY="SELECT padre FROM categoria WHERE id=$id";
  $result=dbSendQuery($QUERY);
  $cat=mysql_fetch_array($result);
  return $cat['padre'];
}

function dbGetUserPartecipatingAuctionsData($id_utente, &$vincendo, &$perdendo, &$vinte, &$perse)
{
  $QUERY = "
  SELECT asta.id AS id_asta,
         UNIX_TIMESTAMP(asta.end_ts) > UNIX_TIMESTAMP(NOW()) AS attiva
  FROM asta, (SELECT DISTINCT id_asta FROM offerta WHERE id_utente = $id_utente) AS partecipate
  WHERE asta.id = partecipate.id_asta
  ";

  $res = dbSendQuery($QUERY);

  while($asta = mysql_fetch_array($res))
  {
    $migliore = mysql_fetch_array(dbGetBestOfferData($asta['id_asta']));

    if(($migliore['id_offerente'] == $id_utente) && dbIsReserveExceed($asta['id_asta'])) $vincente = true;
    else $vincente = false;

    if($asta['attiva'] == 1) $attiva = true;
    else $attiva = false;

    if($attiva && $vincente)
    {
      //Sto vincendo
      $vincendo[] = $asta['id_asta'];
    }
    if(!$attiva && $vincente)
    {
      //Ho vinto
      $vinte[] = $asta['id_asta'];
    }
    if($attiva && !$vincente)
    {
      //Sto perdendo
      $perdendo[] = $asta['id_asta'];
    }
    if(!$attiva && !$vincente)
    {
      //Ho perso
      $perse[] = $asta['id_asta'];
    }
  }
}

function dbDecAuctionReserve($id_asta, $nuova_riserva)
{
  $QUERY = "UPDATE asta SET riserva = $nuova_riserva WHERE id = $id_asta";
  dbSendQuery($QUERY);
}

function dbIsUserAuctionOwner($id_utente, $id_asta)
{
  $QUERY = "
  SELECT *
  FROM asta, oggetto
  WHERE asta.id_oggetto = oggetto.id AND
        asta.id = $id_asta AND
        oggetto.id_utente = $id_utente
  ";

  $res = dbSendQuery($QUERY);

  return mysql_num_rows($res) > 0;
}

function dbGetUserOffers($id_utente)
{
  $QUERY = "
  SELECT offerta.id AS id_offerta,
         offerta.timestamp AS ts_offerta,
         offerta.importo AS importo,
         asta.id AS id_asta,
         oggetto.id AS id_oggetto,
         oggetto.nome AS nome_oggetto
  FROM offerta, asta, oggetto
  WHERE offerta.id_asta = asta.id AND
        asta.id_oggetto = oggetto.id AND
        offerta.id_utente = $id_utente
  ORDER BY id_oggetto, ts_offerta DESC
  ";

  return dbSendQuery($QUERY);
}

function dbGetEndedAuctions()
{
  $QUERY = "
  SELECT id
  FROM asta
  WHERE UNIX_TIMESTAMP(asta.end_ts) < UNIX_TIMESTAMP(NOW())
  ORDER BY end_ts DESC
  ";

  return dbSendQuery($QUERY);
}

function dbIsReserveExceed($id_asta)
{
  if(!($asta = mysql_fetch_array(dbGetAuctionData($id_asta))))
    return false;

  $riserva = $asta['riserva'];

  if($riserva <= $asta['base']) return true;

  if(!($offerta = mysql_fetch_array(dbGetBestOfferData($id_asta))))
    return false;

  return $riserva <= $offerta['importo'];
}
?>